//
//  MyProfileViewController.swift
//  iModern
//
//  Created by Ralf on 5/14/15.
//  Copyright (c) 2015 com.starlooking. All rights reserved.
//

import UIKit

class MyProfileViewController: TableViewController
{
    var articles         = NSMutableArray()
    var appointments     = NSMutableArray()
    var max:    Int      = 10
    var offset: Int      = 0
    var end              = false
    var appDelegate      = UIApplication.sharedApplication().delegate as! AppDelegate
    var articleManager   = ArticleManager()
    let favoritesManager = FavoritesManager()
    let screen          = UIScreen.mainScreen().bounds
    var contact: NSDictionary!

    override func viewDidLoad()
    {
        super.viewDidLoad()

        self.tableView.registerNib(UINib(nibName: "ProfileViewMyAvatarCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "AVATAR")
        self.tableView.registerNib(UINib(nibName: "ProfileOrderManagementCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "MANAGEMENT")
        //        self.tableView.registerNib(UINib(nibName: "ProfileViewMySummaryCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "SUMMARY")
        //        self.tableView.registerNib(UINib(nibName: "ProfileViewArticleCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "ARTICLE")
        //        self.tableView.registerNib(UINib(nibName: "ProfileViewAdvertisingCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "ADVERTISING")
        //        self.tableView.registerNib(UINib(nibName: "ProfileViewTaskCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "Task")
        
        self.tableView.registerNib(UINib(nibName: "ActivityViewAdvertisingCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "ADVERTISING")
        self.tableView.registerNib(UINib(nibName: "ProfileFavoritesCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "FAVORITES")

        self.navigationItem.title = "我的"
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "refresh:", name: "Refresh Market", object: nil)
        
        self.loadData()

    }
    
    @IBAction func refresh(sender: AnyObject)
    {
        self.reloadData(sender)
        self.tableView.reloadData()
    }


    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        
    }

    override func viewWillAppear(animated: Bool)
    {
        initSettingButton()
        self.loadData()

        appDelegate.rootController.navigationItem.leftBarButtonItem = nil
        appDelegate.rootController.navigationItem.titleView = nil
        appDelegate.rootController.navigationItem.title = "我"
    }

    func initSettingButton()
    {
        let button = UIBarButtonItem(image: UIImage(named: "Setting-Small.png")?.imageWithRenderingMode(.AlwaysOriginal), style: .Plain, target: self, action: "loadMenu:")
        appDelegate.rootController.navigationItem.rightBarButtonItem = button
    }

    @IBAction func loadMenu(sender: UIBarButtonItem)
    {
        if (appDelegate.isLogged())
        {
//            let controller = Menu2ViewController()
            let controller = MenusViewController()
            self.pushViewController(controller)
            print("asdfasdfa")
        }
        else
        {
            let controller = LoginViewController()
            self.pushViewController(controller)
        }
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        return articles.count + 3
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {

        let cell: UITableViewCell

        switch indexPath.row
        {
        case 0:
            let c
            = tableView.dequeueReusableCellWithIdentifier("AVATAR", forIndexPath: indexPath) as! ProfileViewMyAvatarCell
            if (appDelegate.isLogged())
            {
                c.setData(self.contact)
            }
            cell = c
            //        case 1:
            //            cell = tableView.dequeueReusableCellWithIdentifier("SUMMARY", forIndexPath: indexPath) as! UITableViewCell
        case 1:
            let c
            = tableView.dequeueReusableCellWithIdentifier("MANAGEMENT", forIndexPath: indexPath) as! ProfileOrderManagementCell
            cell = c
            cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
        case 2:
            let c
            = tableView.dequeueReusableCellWithIdentifier("FAVORITES", forIndexPath: indexPath) as! ProfileFavoritesCell
            cell = c
            cell.userInteractionEnabled = false
            cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator

        default:
            let appointments = articles[indexPath.row - 3] as! NSMutableDictionary
            let cell         = tableView.dequeueReusableCellWithIdentifier("ADVERTISING", forIndexPath: indexPath) as! ActivityViewAdvertisingCell
            cell.setData(appointments)
            return cell
        }
        return cell
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return NO if you do not want the specified item to be editable.
    return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
    // Delete the row from the data source
    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    } else if editingStyle == .Insert {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
    
    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return NO if you do not want the item to be re-orderable.
    return true
    }
    */

    /*
    // MARK: - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    }
    */

    func loadData()
    {
        if (end)
        {
            return;
        }

        if (appDelegate.isLogged())
        {
            //            appDelegate.contactManager.loadContact()
            //            self.contact = appDelegate.contactManager.contact
            //
            //            let userName = self.contact["userName"] as! String
            //            let rs       = articleManager.queryByUserName(userName, max: max, offset: offset)
            //
            //            if (self.verifyResutSet(rs))
            //            {
            //                if (rs.isEmpty())
            //                {
            //                    end = true
            //                }
            //                else
            //                {
            //                    articles.addObjectsFromArray(rs.toMutableArray() as [AnyObject])
            //                    offset = articles.count
            //                }
            //            }
            //            appointment
            appDelegate.contactManager.loadContact()
            self.contact = appDelegate.contactManager.contact

            let rs = favoritesManager.queryFavoritesBySessionID(max, offset: offset)
            if (self.verifyResutSet(rs))
            {
                if (rs.isEmpty())
                {
                    end = true
                }
                else
                {
                    articles.addObjectsFromArray(rs.toMutableArray() as [AnyObject])
                    offset = articles.count
                }
            }
        }

        self.tableView.reloadData()
    }

    @IBAction override func reloadData(sender: AnyObject?)
    {
        offset = 0
        end = false
        articles.removeAllObjects()
        self.loadData()
        super.reloadData(sender)
    }

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        let screen = UIScreen.mainScreen().bounds
        switch indexPath.row
        {
        case 0:
            return 200
            //        case 1:
            //            return 40
        case 1:
            return 40
        case 2:
            return 40
        default:
            let message       = articles.objectAtIndex(indexPath.row - 3).objectForKey("article")?.objectForKey("message") as! NSString
            let messageHeight = sizeOfText(message).height
            return screen.size.width + 100 + messageHeight + 10
        }
    }
    
    func sizeOfText(text: NSString) -> CGSize
    {
        let paragraphStyle = NSMutableParagraphStyle()
        
        paragraphStyle.lineHeightMultiple = 16
        paragraphStyle.maximumLineHeight = 20
        paragraphStyle.minimumLineHeight = 20
        
        //        paragraphStyle.firstLineHeadIndent = 20
        paragraphStyle.alignment = .Left
        
        let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(14),
            NSParagraphStyleAttributeName: paragraphStyle,
            NSForegroundColorAttributeName: UIColor.darkGrayColor()]
        
        let frame = CGSizeMake(screen.size.width, screen.size.height)
        let options = unsafeBitCast(NSStringDrawingOptions.TruncatesLastVisibleLine.rawValue|NSStringDrawingOptions.UsesLineFragmentOrigin.rawValue |
            NSStringDrawingOptions.UsesFontLeading.rawValue,
            NSStringDrawingOptions.self)
        let size  = text.boundingRectWithSize(frame, options: options, attributes: attributes, context: nil)
        return size.size
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        //         var activity = appointments[indexPath.row - 2] as! NSMutableDictionary
        switch indexPath.row
        {
        case 1:
            let controller = MyOrderViewController()
            self.pushViewController(controller)
        case 2:
            return
        default:
            let controller = AdvertisingPageViewController()
            controller.activity = articles[indexPath.row - 3] as! NSMutableDictionary
            self.pushViewController(controller)
        }

    }
}
